<template>
  <x-layout-main>
    <template #header>
      <x-form ref="filterFormRef" v-model:model="formData" inline label-placement="left">
        <n-form-item label="岗位名称" path="roleName">
          <n-input
            v-model:value="formData.roleName"
            clearable
            placeholder="请输入岗位名称"
            @keyup.enter="immediate = true"
          />
        </n-form-item>
        <n-form-item>
          <x-button icon="icon-076" type="primary" @click="immediate = true">查询</x-button>
          <x-button icon="icon-074" @click="resetForm">重置</x-button>
        </n-form-item>
      </x-form>
    </template>
    <n-card :segmented="{ content: true }" :bordered="false" size="small">
      <x-data-table ref="tableElRef" v-model:immediate="immediate" :params="params" :columns="columns">
        <template #tableTitle>
          <x-button icon="icon-037" type="primary" @click="onAdd">新建岗位</x-button>
        </template>
      </x-data-table>
    </n-card>
    <create-role-modal v-if="createModalData.show" :modal-data="createModalData" />
  </x-layout-main>
</template>

<script lang="ts">
  import { computed, defineComponent, h, reactive, ref, toRefs } from 'vue'
  import { XDataTable, XLayoutMain, XDrawer, XForm, XButton } from '@/components'
  import {
    NSpace,
    NSpin,
    NCard,
    NFormItem,
    NInput,
    NTree,
    NRadio,
    NRadioGroup,
    NTag,
    NSelect,
    useMessage,
    TreeOption,
    NModal,
    NPopconfirm
  } from 'naive-ui'
  import { useStore } from '@/store'
  import { SystemRoleParams } from '@/api/model/systemModel'
  import { filterCheckedIds, getTreeItem } from '@/utils'
  import { useAuthority, useDictionary } from '@/hooks'
  import CreateRoleModal from '@/views/system/role/components/CreateRoleModal.vue'
  import { useRouter } from 'vue-router'

  export default defineComponent({
    name: 'ShopVersion',
    components: {
      CreateRoleModal,
      NSpace,
      NSpin,
      NCard,
      NFormItem,
      NInput,
      NTree,
      NRadio,
      NRadioGroup,
      XDataTable,
      XLayoutMain,
      NModal,
      XForm,
      XButton,
      NPopconfirm
    },
    setup() {
      const router = useRouter()
      const $authority = useAuthority()
      const $dictionary = useDictionary()
      $dictionary.get('ROLE_STATUS,RESOURCE_DATA_RANGE')
      const $store = useStore()
      const $message = useMessage()
      const formRef: any = ref(null)
      const filterFormRef: any = ref(null)
      const dataRangeList = ref<{ resourceId: string; dataRange: number }[]>([])
      const $state: any = reactive({
        createModalData: {
          show: false
        },
        dialogVisible: false,
        immediate: true,
        loading: false,
        params: computed(() => {
          return {
            actions: 'system/getSystemRle',
            data: {
              ...$state.formData
            }
          }
        }),
        formData: {
          roleName: null
        },
        isViews: false,
        currentRow: null,
        list: null,
        dictionary: computed(() => {
          return $store.getters.dictionary
        }),
        editTitle: computed(() => {
          return $state.isViews ? '查看权限' : $state.currentRow && $state.currentRow.id ? '编辑岗位' : '新建岗位'
        }),
        columns: [
          {
            title: '岗位名称',
            key: 'roleName'
          },
          {
            title: '岗位描述',
            key: 'roleDesc'
          },
          {
            title: '员工数量',
            key: 'accountCount',
            render(row: any) {
              return h(XButton, { type: 'primary', text: true }, () => row.accountCount)
            }
          },
          {
            title: '创建时间',
            key: 'createdAt'
          },
          {
            title: '操作',
            align: 'center',
            key: 'tools',
            width: '100px',
            render(row: SystemRoleParams) {
              return h(NSpace, {}, () => [
                h(
                  XButton,
                  {
                    text: true,
                    size: 'small',
                    type: 'primary',
                    onClick: (e: any) => {
                      e.stopPropagation()
                      $state.isViews = false
                      handleEditDetail(row)
                    }
                  },
                  () => '编辑'
                ),
                h(
                  NPopconfirm,
                  { onPositiveClick: () => handleDelete(row) },
                  {
                    default: () => '确认删除？',
                    trigger: () =>
                      h(
                        XButton,
                        {
                          text: true,
                          size: 'small',
                          type: 'primary'
                        },
                        () => '删除'
                      )
                  }
                )
              ])
            }
          }
        ]
      })

      // 获取权限数据
      $store
        .dispatch('system/getSystemAuthority', {
          platformType: 2
        })
        .then((res) => {
          $state.list = res.data
        })

      // 重置
      const resetForm = () => {
        filterFormRef.value.resetFields()
        $state.immediate = true
      }

      // 新增
      const onAdd = () => {
        router.push({
          name: 'SystemRoleEdit'
        })
      }

      // 编辑
      const handleEditDetail = (row: SystemRoleParams) => {
        router.push({
          name: 'SystemRoleEdit',
          query: {
            roleId: row?.id
          }
        })
      }

      const handleDelete = async (row: SystemRoleParams) => {
        await $store.dispatch('system/getSystemRleDelete', {
          id: row.id
        })
        $state.immediate = true
      }

      // 取消
      const handleCancel = () => {
        $state.dialogVisible = false
      }
      // 权限切换
      const handleCheckedKeys = (row: number[]) => {
        $state.currentRow.resourceIds = row
      }

      function getDataRangeList(list, ret = []) {
        list.forEach((item) => {
          if (item.dataStatus) {
            ret.push(item)
          }
          if (item.children?.[0]) {
            getDataRangeList(item.children, ret)
          }
        })

        return ret.map((item) => ({
          resourceId: item.id,
          dataRange: item.dataRange
        }))
      }

      // 提交
      const submitForm = () => {
        formRef.value.validate((errors: []) => {
          if (!errors) {
            $state.loading = true
            // 通过当前选中的子级id串，再关联对应父级id，全部返回给服务端
            const resourceIds = [...$state.currentRow.resourceIds]
            try {
              console.log($state.currentRow, 1111111)
              $state.currentRow.resourceIds.forEach((key: number) => {
                const parentIds = getTreeItem($state.list, key)?.parentIds as []
                resourceIds.push(...parentIds)
              })
              const params = {
                id: $state.currentRow.id || null,
                resourceIds: [...new Set(resourceIds)],
                roleName: $state.currentRow.roleName,
                roleStatus: $state.currentRow.roleStatus,
                dataRangeList: getDataRangeList($state.list)
              }
              console.log(params, 'params')
              $store
                .dispatch('system/setSystemRleDetail', params)
                .then(() => {
                  $message.success('执行成功')
                  $state.loading = false
                  $state.dialogVisible = false
                  $state.immediate = true
                  $state.currentRow = null
                })
                .catch(() => {
                  $state.loading = false
                })
            } catch (e) {
              console.log(e)
            }
          } else {
            $message.warning('验证失败，请填写完整信息')
          }
        })
      }

      return {
        ...toRefs($state),
        formRef,
        filterFormRef,
        onAdd,
        handleCancel,
        handleCheckedKeys,
        submitForm,
        resetForm
      }
    }
  })
</script>

<style></style>
